﻿#if UNITY_ANDROID || UNITY_IOS

using UnityEngine;
using System.Runtime.InteropServices;

public class HeadPhoneDetect : MonoBehaviour
{
    // Start is called before the first frame update
    private bool bWiredHeadPhone = false;
    private bool bBTHeadPhone = false;
#if UNITY_ANDROID
    private AndroidJavaObject javaClass;
#elif UNITY_IOS
    [DllImport("__Internal")]
    private static extern void _AddRouteChangeListener();
    [DllImport("__Internal")]
    private static extern bool _IsHeadPhoneConnected();
#endif

    void Start()
    {
#if UNITY_ANDROID
        javaClass = new AndroidJavaObject("com.GA.AndroidTest.MainActivity");
#elif UNITY_IOS
        RegistListener();
        bWiredHeadPhone = _IsHeadPhoneConnected();
        ChangeState();
#endif
    }

#if UNITY_IOS
    public static void RegistListener()
    {
        _AddRouteChangeListener();
    }
#endif
    public void OnWiredHeadPhoneConnected(string p)
    {
        bWiredHeadPhone = true;
        bBTHeadPhone = IsBTHeadPhoneConnected();
        ChangeState();
    }

    public void OnWiredHeadPhoneDisConnected(string p)
    {
        bWiredHeadPhone = false;
#if UNITY_ANDROID
        bBTHeadPhone = IsBTHeadPhoneConnected();
#endif
        ChangeState();
    }

    public void OnBTHeadPhoneConnected(string p)
    {
        bBTHeadPhone = true;
        ChangeState();
    }

    public void OnBTHeadPhoneDisConnected(string p)
    {
        bBTHeadPhone = false;
        ChangeState();
    }

    public bool IsBTHeadPhoneConnected()
    {
        bool btc = false;
#if UNITY_ANDROID
        using (AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
             btc = javaClass.Call<bool>("isBluetoothHeadsetConnected");
        }
#endif
        return btc;
    }

    public void ChangeState()
    {
        UnityEngine.Debug.LogError("Wired HeadPhone : " + bWiredHeadPhone);
        UnityEngine.Debug.LogError("BlueTooth HeadPhone : " + bBTHeadPhone);
    }
}
#endif